import {
  Body,
  Controller,
  Get,
  HttpStatus,
  Inject,
  Post,
  Req,
  Request,
  Res,
  Session,
  UnauthorizedException,
  UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { VerificationCodeService } from 'src/component/code/verification-code.service';
import { ToolsService } from 'src/utils/tools.service';
import { AuthService } from './auth.service';
import { Logger } from 'src/utils/log4js';
import * as Chalk from 'chalk';
// import { CurrentUser } from './auth.decorator';

@Controller('auth')
export class AuthController {
  @Inject()
  private readonly verificationCodeService: VerificationCodeService;

  constructor(private readonly authService: AuthService) {}

  @Get('authcode') //当请求该接口时，返回一张随机图片验证码
  async getCode(@Req() req, @Res() res) {
    const svgCaptcha = await this.verificationCodeService.captche(); //创建验证码
    Logger.log(Chalk.yellow(svgCaptcha.text));
    req.session.code = svgCaptcha.text; //使用session保存验证，用于登陆时验证
    this.verificationCodeService.saveCode(svgCaptcha.text);
    res.type('image/svg+xml'); //指定返回的类型
    res.send(svgCaptcha.data); //给页面返回一张图片
  }

  // 登录测试
  @UseGuards(AuthGuard('local')) //本地策略，传递local，执行local里面的validate方法
  @Post('login')
  async login(@Request() req, @Body() body, @Session() session) {
    //验证验证码，由前端传递过来
    const { code } = body;
    if (code?.toUpperCase() === session.code?.toUpperCase()) {
      console.log('验证码通过');
      //通过req可以获取到validate方法返回的user，传递给login，登陆
      return this.authService.login(req.user);
    } else {
      ToolsService.fail('验证码错误');
    }
  }

  // 测试登录后才可访问的接口，在需要的地方使用守卫，可保证必须携带token才能访问
  @Get('user')
  @UseGuards(AuthGuard('jwt')) //jwt策略，身份鉴权
  //通过req获取到被验证后的user，也可以使用装饰器
  getProfile(@Request() req) {
    console.log('req', req.user);
    return req.user;
  }
}
